<template>
	<view class="history_details backgroundSty">
	    <view class="history_detailsbg">
	        <view class="history_details_doctor">
	            <view><image :src="doctorInfos.headPic"></image></view>
	            <view calss="cnt">
	                <view class="name">
	                <text>{{doctorInfos.doctorName}}</text> {{doctorInfos.deptName}} | {{doctorInfos.titles}}
	                </view>
	                <view class="describe">请描述您的性别、年龄、症状、就诊经历，我将竭诚为您服务，并保障您的隐私安全</view>
	            </view>
	        </view>
	        <view class="history_details_addbtn" @click.native="handleAddPatient('open')">+新建患者</view>
            <view class="history_details_patient" v-if="patientList.length>0">
               <uni-tabs :list="patientList" v-model="selectPatientIndex"   v-on:select-index="selectIndex" :lineAnimated="false"></uni-tabs> 
            </view>
	    </view>
        <view class="history_details_cnt">
            <textarea v-if="modalColse" :value="describe" @input="bindinput" @blur="bindinput" maxlength="100" :class="[describeStyle?'history_details_textarea active':'history_details_textarea'] "  auto-height placeholder="请在此描述详情(描述内容最少10字)" />
            <view class="history_details_camera">
                <image @click.native="uploadPictures" data-text="open" src="../../../static/images/weibiao.png"></image>
                <view  class="uploadImg" v-if="photosList.length>0" >
                    <view class="chart_img" v-for="(image, index) in photosList" :for-index="index" :key="index" :for-item="image">
                        <image   mode='aspectFill' :src="image"  @click.native="previewImage(image,photosList)"></image>
                        <i class="iconfont icon-close-b" @click.native="closeImg(index)"></i>
                    </view>
                </view>
                <text v-if="photosList.length==0">您可上传９张图片资料，仅解答的医生可见</text>
            </view>
        </view>
        <view  class="history_details_footer">
            <view>医生将在24小时内回复您，超时未回复会自动退款；</view>
            <view>医生回复后，订单将在支付后的第48小时关闭订单。</view>
        </view>
        <view class="flexAverage history_details_pay">
            <view class="fl">合计<text>￥{{doctorInfos.price}}</text></view>
            <view class="fr" @click.native="pay">立即支付</view>
        </view>
        <!-- 新建患者 -->
        <view class="modal-style" :hidden="modalColse" >
            <form class="history_details_addcnt">
                <view class="title">新建患者</view>
                <view class="row">
                    <text>姓名</text>
                    <input class="uni-input" :value="patientName" data-text="name" @input="bindForm"  @blur="bindForm"  maxlength="6" placeholder="请输入姓名" />
                </view>
                <view class="row">
                    <text>出生日期</text>
                    <picker mode="date" :value="nowDate"  @change="bindForm" data-text="date">
                        <view class="picker">
                            {{nowDate}}
                        </view>
                        <text class="iconfont icon-rili"></text>
                    </picker>
                </view>
               <view class="row">
                    <text>性别</text>
                    <radio-group name="sex" :value="sex"  @change="bindForm" data-text="sex">
                        <label v-for="(item, index) in sexItems" :key="item.name"   >
                            <radio class="radio" :value="item.value" :checked="item.checked"/>{{item.name}}
                        </label>
                    </radio-group>
                </view>
                <view class="flexAverage footer">
                    <view class="fl" @click.native="handleAddPatient('close')">取消</view>
                    <view class="fr" @click.native="addSubmit">保存</view>
                </view>
            </form>
        </view>
	</view>
</template>
<script>
    import uniTabs from '@/components/uni-ui/uni-tabs/uni-tabs.vue';
    import moment from '@/common/util/moment.min.js';
    import _ from '@/common/util/underscore.js';
    import API from '@/utils/api.js';
	export default {
		data() {
			return {
				modalColse: true,
                sexItems: [
                    { name: '男', value: '1', checked: 'true' },
                    { name: '女', value: '2' }
                ],
                describeStyle: false,//描述的样式显示红色
                doctorInfos: {},//医生信息
                //新增患者的数据 表单
                patientName: "",
                sex: 1,
                nowDate: "",
                patientList: [],//患者列表
                selectPatientIndex:0,//选中患者
                selectPatientInfos: {},//选中患者信息
                describe: "",//描述
                photosList: [],//前端显示图片地址
                picUrl:[]//是保存记录的时候传给后端
			}
		},
		components:{
            uniTabs
		},
		onLoad(option) {
            let params ={
                deptId: "1",
                deptName: "儿科",
                doctorId: "doctor02",
                doctorName: "李医生",
                headPic: "https://twzx.obs.cn-south-1.myhuaweicloud.com/1581584363170",
                price: "0",
                titles: "医师"
            }
            this.doctorInfos = params || option;
            this.nowDate = moment().format("YYYY-MM-DD");
            this.itemNum = parseInt(this.patientList.length) < 3 ? this.patientList.length : 3;
            this.getPatient();
		},
		methods: {
            // 选中的患者
            selectIndex: function (e) {
                this.selectPatientIndex = e;
                this.selectPatientInfos = this.patientList.length>0?this.patientList[e]:{};
            },
             //描述内容 键盘触发的时候
            bindinput: function (e) {
                this.describe =  e.detail.value,
                this.describeStyle = e.detail.value.length < 10 ? true : false
            },
            //添加图片
            uploadPictures: function () {
                let _this = this;
                console.log(this.picUrl, this.picUrl.length, "图片2222")
                if (this.picUrl.length >= 9) {
                    uni.showToast({
                        title: '添加图片最多9张',
                        icon: 'none',
                        duration: 1000
                    })
                    return;
                }
                uni.chooseImage({
                    count: 3,
                    sizeType: ['original', 'compressed'],
                    sourceType: ['album', 'camera'],
                    success: function (res) {
                        let imgPaths = res.tempFilePaths;
                        for(var i=0;i<imgPaths.length;i++){
                            _this.uploadImg(_this,imgPaths[i]);
                        }
                    }
                });
            },
            //删除图片
            closeImg: function (index) {
                let photosList = [].concat(this.photosList);
                let picUrl = [].concat(this.picUrl);
                photosList.splice(index, 1);
                picUrl.splice(index, 1);
                this.photosList = photosList;
                this.picUrl = picUrl;
            },
            //预览图片
            previewImage: function (current,list) {
                uni.previewImage({
                    current: current, // 当前显示图片的http链接
                    urls: list // 需要预览的图片http链接列表
                })
            }, 
			//查询患者
            getPatient: function () {
                let params = {
                    hospitalId:uni.getStorageSync('hospitalId'),
                    patientUserId: uni.getStorageSync('patientUserId')
                }
                API.getPati(params).then(res => {
                    if (res.success == true) {
                        let entity = res.entity;
                        
                        if (entity.length > 0) {
                            entity = _.map(entity, function (el) {
                                el.patientName = el.patientName == null ? "" : el.patientName;
                                el.sex = el.sex == "1" ? "男" : "女";
                                el.title = el.patientName + "|" + el.sex + "|" + el.age;
                                return el;
                            });
        
                        }
                        this.patientList = entity;
                        this.selectPatientIndex =0;
                        this.selectPatientInfos = entity.length > 0 ? entity[0] : {};
                    }
                })
            },
             // 新增患者 弹出框操作
            handleAddPatient: function (types) {
                let  _this = this;
                let sexItems = _.map(this.sexItems, function (row) {
                    row.checked = row.value == "1" ? true : false;
                    return row;
                });
                this.sexItems = sexItems;
                this.$set(this.sexItems[0],'checked',true);
                this.patientName = "";
                this.nowDate = moment().format("YYYY-MM-DD");
                this.sex = 1;
                this.$forceUpdate();
                if (types === "open") {
                   this.modalColse = false;
                } else if (types === "close") {
                   this.modalColse = true;
                }
            },
            //新患者表单输入
            bindForm: function (e) {
                if (e.currentTarget.dataset.text === "name") {
                    this.patientName = e.detail.value;
                } else if (e.currentTarget.dataset.text === "date") {
                    var toDate = new Date(moment().format("YYYY-MM-DD"));
                    var now = new Date(e.detail.value);
                    if (now.getTime() > toDate.getTime()) {
                        uni.showToast({
                            title: '请重新选择，出生日期不能大于今天的日期',
                            icon: 'none',
                            duration: 1500
                        })
                        return false;
                    }
                    this.nowDate = e.detail.value;
                } else {
                    this.sex = e.detail.value;
                }
            },
            //新建患者 保存按钮
            addSubmit: function () {
                let newData = [];
                newData = {
                    patientName: this.patientName,
                    birthday: this.nowDate,
                    sex: this.sex
                }
                let isNull = false;
                for (let i in newData) {
                    if (newData[i] == "") {
                        isNull = true;
                    }
                }
                if (isNull === true) {
                    uni.showToast({
                        title: '请填写所有信息',
                        icon: 'none',
                        duration: 1000
                    })
                    return;
                }
                let patientList = this.patientList;
                newData.openid = uni.getStorageSync('openid');
                newData.idcard = "";//身份证号
                newData.patientNo = "";//就诊卡号
                newData.hospitalId = uni.getStorageSync('hospitalId');
                newData.patientUserId = uni.getStorageSync('patientUserId');//患者id
                API.addPati(newData).then(res => {
                    if (res.success == true) {
                        uni.showToast({
                            title: '新增患者成功',
                            icon: 'none',
                            duration: 1000
                        })
                        this.getPatient();
                        this.modalColse = true;
                    }
                }) 
            },
            // 上传图片
            uploadImg:function(mythis,imgPaths){
                let photosUrl = [], photosListshow=[];// photosUrl传给后端的地址，photosListshow前端展示的地址
                uni.uploadFile({
                    url: API.upload(), //仅为示例，非真实的接口地址 "https://twzx.191cn.com/pat-api/file/upload",//
                    filePath: imgPaths,
                    name: 'file',//这个是根据后台接口写的名字文件对应的 key，开发者在服务端可以通过这个 key 获取文件的二进制内容
                    header: {
                        'Content-Type': 'multipart/form-data'
                    },
                    formData: {
                        'file': imgPaths
                    },
                    success: function (e) {
                        let res = JSON.parse(e.data);
                        if (res.success == true) {
                            photosUrl = mythis.picUrl;
                            photosListshow = mythis.photosList;
                            photosListshow.push(imgPaths);
                            photosUrl.push(res.entity);
                            mythis.photosList = photosListshow;
                            mythis.picUrl= photosUrl;
                        }
                    }
                })
                
            },
             //立即支付
            pay: function () {
                if (this.describe === "" || this.describe.length < 10) {
                    wx.showToast({
                        title: '描述信息不能为空且不能少于10个字',
                        icon: 'none',
                        duration: 1000
                    })
                    return;
                }
                // 支付时验证是否选择患者、咨询服务是否上架、医生是否正常咨询，未上架跳转通用异常页，非正常咨询予以提示，不允许结算
                if (JSON.stringify(this.selectPatientInfos) == "{}") {
                    wx.showToast({
                        title: '请选择患者',
                        icon: 'none',
                        duration: 1000
                    })
                    return;
                }
                let params = {
                    describe: this.describe,//描述
                    patientId: this.selectPatientInfos.patientId,
                    hospitalId: uni.getStorageSync('hospitalId'),
                    patientName: this.selectPatientInfos.patientName,
                    sex: this.selectPatientInfos.sex == "男" ? 1 : 2,
                    birthday: this.nowDate,
                    deptId: this.doctorInfos.deptId,
                    deptName: this.doctorInfos.deptName,
                    doctorId: this.doctorInfos.doctorId,
                    doctorName: this.doctorInfos.doctorName,
                    money: this.doctorInfos.price,
                    titles: this.doctorInfos.titles,
                    question: this.describe,
                    picUrl: this.picUrl.toString(),
                    patientUserId: uni.getStorageSync('patientUserId'),
                    openid:uni.getStorageSync('openid')
                }
                API.addOrder(params).then(res => {
                    if (res.success == true) {
                        uni.showModal({
                            title: "下单成功",
                            content: "请等待医生回复咨询问题",
                            showCancel: false,
                            confirmText: "我知道了",
                            success(res) {
                                if (res.confirm) {
                                    uni.navigateTo({
                                        url: '/pages/consultation/advisoryRecord/index',
                                    })
                                }
                            }
                        })
                    } else {
                        //异常情况
                        uni.showModal({
                            content: res.message,
                            showCancel: false,
                            confirmText: "我知道了",
                            success(res) {
                                if (res.confirm) {
                                    uni.navigateTo({
                                        url: '/pages/exception/index',
                                    })
                                }
                            }
                        })
                    }
                })
            }
		}
	}
</script>

<style scoped lang="scss">
	page,.body,html{
	    background: #efeff4;
	}
	.history_details{
	    padding-bottom: 100rpx;
	}
	.history_details_doctor{
	    display: flex;
	    padding: 28rpx 30rpx 40rpx 30rpx;
	    border-bottom: 1.5rpx solid  #d1d1d5;
	    margin-bottom: 30rpx;
        image{
        	width: 135rpx;
        	height:135rpx;
            margin-right: 50rpx;
            border-radius: 50%;
        }
        .name{
            font-size: 28rpx;
            color: #999999;
            text{
                font-size:42rpx;
                color: #222;
                margin-right: 20rpx;
                font-weight: 700;
            }
        }
        .describe{
            margin-top: 30rpx;
            background-color: #ecf5ff;
            font-size: 24rpx;
            padding: 21rpx;
        	color: #499dff;
        }
	}
	.history_detailsbg{
	    background: #fff;
	}
	.history_details_addbtn{
	    width: 264rpx;
		height: 60rpx;
	    line-height: 60rpx;
		background-color: #499dff;
		border-radius: 30rpx;
	    margin: auto;
	    letter-spacing: 2px;
	    font-size: 30rpx;
	    text-align: center;
	    color: #fff;
	}
    /* 患者列表 */
	.history_details_patient{
	    padding-left: 32rpx;
	    margin-top: 25rpx;
	}
	.history_details_cnt{
	    padding: 20rpx 32rpx 32rpx;
	    background: #fff;
	}
	.history_details_textarea{
	    margin: 0rpx 0 30rpx; 
	    min-height: 310rpx;
	    background-color: #eeeff2;
		border-radius: 8px;
	    width: 100%;
	    padding: 30rpx;
	    letter-spacing: 2px;
		color: #999999;
	    font-size: 26rpx;
	    box-sizing: border-box;
	    line-height: 50rpx;
	}
	.history_details_textarea.active{
	    color: #f00;
	}
	.history_details_camera{
	    letter-spacing: 2rpx;
		color: #999999;
	    font-size: 26rpx;
	    display: flex;
        image{
            width: 100rpx;
            height: 100rpx;
            margin-right: 15rpx;
            margin-bottom: 15rpx;
        }
        .uploadImg{
            flex: 1 1;
            margin-right: 15rpx;
        }
        .chart_img{
            float: left;
            width: 100rpx;
            height: 100rpx;
            margin-right: 15rpx;
            margin-left: 0;
            margin-bottom: 15rpx;
            position: relative
        }
        .chart_img i{
            position: absolute;
            top: -10rpx;
            right:-20rpx;
            color: #f00;
            background: #fff;
            border-radius: 50%;
            border:8rpx solid #fff;
        }
        text{
            flex: 1 1;
            margin-left: 28rpx;
            line-height: 100rpx;
        }
	}
	
	.history_details_footer{
	    padding: 30rpx;
	    background-color: #efeff4;
	    letter-spacing: 2rpx;
		color: #499dff;
	    font-size: 24rpx;
	}
	.history_details_pay{
	    position: fixed;
	    bottom: 0;
	    left: 0;
	    right: 0;
	    font-size: 30rpx;
	    line-height: 100rpx;
	    letter-spacing: 2px;
	    font-weight: bold;
	    z-index: 2;
	    background: #fff;
        .fl{
            padding-left: 28rpx;
        }
        .fl text{
            color: #ff3300;
            margin-left: 20rpx;
        }
        .fr{
            text-align: center;
        	color: #ffffff;
            background-color: #499dff;
        }
	}
	
	/* 新建患者弹出框 */
	.history_details_addcnt{
		background: #fff;
		border-radius: 8rpx;
		position: absolute;
		top:50%;
		left:50%;
		width: 80%;
		margin-top:-258rpx;
		margin-left: -40%;
		height: 516rpx;
	    z-index: 3333;
        .title{
        	text-align: center;
            font-size: 32rpx;
            height: 90rpx;
            line-height: 90rpx;
            letter-spacing: 2rpx;
        	color: #fdfdfd;
        	background-color: #499dff;
        	border-top-left-radius:8rpx;
        	border-top-right-radius:8rpx;
            font-weight: 700;
            margin-bottom: 50rpx;
        }
        .row{
            line-height: 60rpx;
            font-size: 28rpx;
            margin-bottom: 30rpx;
            text{
                width: 30%;
                text-align: right;
                font-size: 24rpx;
                letter-spacing: 2rpx;
            	color: #000000;
                display: inline-block;
            }
            input{
                width: 45%;
                margin-left: 60rpx;
                display: inline-block;
                background: #fff;
                height: 60rpx;
                color: #999999;
                border-radius: 5rpx;
            	border: solid 1rpx #bcbcbc;
                font-size: 24rpx;
                overflow: inherit;
                padding: 0 15rpx;
            }
            picker{
                width: 45%;
                font-size: 24rpx;
                margin-left: 60rpx;
                padding: 0 15rpx;
                border-radius: 5rpx;
            	border: solid 1rpx #bcbcbc;
                display: inline-block;
                position: relative;
            }
            text.icon-rili{
                position: absolute;
                top: 0;
                right: 20rpx;
                z-index: 2;
                color: #499dff;
                width: 31rpx;
            }
            radio-group{
                width: 45%;
                margin-left: 60rpx;
                display: inline-block;
            }
            radio-group label{
                margin-right: 20rpx;
            }
            radio-group .radio{
               transform: scale(0.6);
            }
        }
        .footer{
            border-top:1rpx solid #efeff4;
            text-align: center;
            letter-spacing: 2px;
            height: 94rpx;
            font-size: 28rpx;
            font-weight: 700;
            position: relative;
            view{
                line-height: 94rpx;
            }
            .fl{
                color: #959595;
            }
            .fr{
                color: #499dff;
            }
            &:after{
                content: '';
                position: absolute;
                top:35rpx;
                left: 50%;
                width: 4rpx;
                height: 28rpx;
                background: #efeff4;
                z-index: 1;
            }
        }
	}

	
</style>
